<template>
  <div class="reprocessedPlastic" v-loading="loading">
    <div class="title">产品信息（再生塑料）</div>
    <el-divider></el-divider>

    <!-- 基本信息 -->
    <div class="companyInformation">
      <div class="content">
        <!-- 左侧表单 -->
        <div class="left">
          <div class="info">
            <!-- <el-form ref="form" :model="form" label-width="80px"> -->
            <el-form label-width="80px" :disabled="disabled">
              <el-form-item label="品名">
                <el-select
                  v-model="brand"
                  placeholder="请选择品名"
                  ref="brandScroll"
                >
                  <el-option
                    v-for="item in brandOptions"
                    :key="item.value"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="产品信息标题">
                <el-input
                  placeholder="请正确输入产品信息标题"
                  v-model="productTitle"
                  maxlength="25"
                ></el-input>
              </el-form-item>

              <el-form-item label="单价">
                <el-input
                  placeholder="请输入真实价格"
                  v-model="price"
                ></el-input>
                <span class="word">元/吨</span>
              </el-form-item>

              <el-form-item label="数量">
                <el-input placeholder="请输入数量" v-model="number"></el-input>
                <span class="word">吨</span>
              </el-form-item>

              <div class="companytype">
                <div class="leftText">是否含税</div>
                <div
                  class="selectItem"
                  v-for="(item, index) in itemList"
                  :key="index"
                  @click="selectTax(index)"
                >
                  <img
                    src="../../assets/bussiness/btn_dl_sel@2x.png"
                    class="checkImage"
                    alt=""
                    v-if="currentIndex == index"
                  />
                  <div class="checkbox" v-else></div>
                  {{ item.name }}
                </div>
              </div>

              <!-- <el-form-item label="是否含税">
                <el-checkbox-group v-model="type" :max="max">
                  <el-checkbox label="是" name="type"></el-checkbox>
                  <el-checkbox label="否" name="type"></el-checkbox>
                </el-checkbox-group>
              </el-form-item> -->

              <el-form-item label="免费试样">
                <el-input
                  placeholder="不提供试样请输入0"
                  v-model="sample"
                ></el-input>
                <span class="word">公斤</span>
              </el-form-item>

              <el-form-item label="交货地">
                <el-cascader
                  placeholder="请选择交货地"
                  :options="addressList"
                  :props="{ expandTrigger: 'hover', value: 'label' }"
                  @change="handleChange"
                  v-model="handleAddress"
                ></el-cascader>
              </el-form-item>

              <el-form-item label="有效期">
                <el-input
                  placeholder="请输入有效时间：长期/30天/10天"
                  v-model="usefulLife"
                ></el-input>
              </el-form-item>

              <el-form-item label="品牌">
                <el-input placeholder="请输入品牌" v-model="kind"></el-input>
              </el-form-item>

              <el-form-item label="生产商">
                <el-input
                  placeholder="请输入生产商"
                  v-model="producer"
                ></el-input>
              </el-form-item>

              <el-form-item label="颜色">
                <el-input
                  placeholder="请输入产品颜色"
                  v-model="color"
                ></el-input>
              </el-form-item>

              <el-form-item label="型号">
                <el-input
                  placeholder="请输入产品型号"
                  v-model="typeNumber"
                ></el-input>
              </el-form-item>

              <el-form-item label="形状">
                <el-select v-model="shape" placeholder="请正确选择">
                  <el-option
                    v-for="item in shapeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="级别">
                <el-select v-model="level" placeholder="请正确选择">
                  <el-option
                    v-for="item in levelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="产品特性">
                <el-select
                  v-model="trait"
                  placeholder="请正确选择"
                  :multiple="true"
                  :multiple-limit="3"
                >
                  <el-option
                    v-for="item in traitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="产品用途">
                <el-select
                  v-model="use"
                  placeholder="请正确选择"
                  :multiple="true"
                  :multiple-limit="3"
                >
                  <el-option
                    v-for="item in useOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 右侧上传处 -->
        <div class="right">
          <div class="store">
            <div class="leftText">图片</div>
            <div class="uploadPlace">
              <el-upload
                :disabled="disabled"
                :class="{ hide: fifthImage }"
                :action="imgUpload"
                accept="image/*"
                list-type="picture-card"
                :limit="5"
                :on-success="successChange"
                :on-remove="hideLogo"
                :file-list="pictureList"
              >
                <div class="uplogo">
                  <img
                    src="../../assets/bussiness/icon_rzgys_sc@2x.png"
                    alt=""
                    class="image"
                  />
                  <span class="text">请上传</span>
                </div>
              </el-upload>
              <span>（最多上传5张）</span>
            </div>
          </div>

          <div class="video">
            <div class="leftText">视频</div>
            <div class="uploadPlace">
              <el-upload
                :disabled="disabled"
                accept="video/*"
                ref="videoUpload"
                :action="imgUpload"
                list-type="picture-card"
                :multiple="false"
                :show-file-list="false"
                :on-progress="progressProduct"
                :on-success="productSuccess"
                :on-remove="hideproduct"
              >
                <div
                  class="uplogo"
                  v-if="videoUrl == ''"
                  :class="{ hide: videoUrl }"
                >
                  <img
                    src="../../assets/bussiness/icon_rzgys_sc@2x.png"
                    alt=""
                    class="image"
                  />
                  <span class="text">请上传</span>
                </div>
                <img
                  class="closeIcon"
                  src="../../assets/bussiness/gb@3x.png"
                  v-if="videoUrl"
                  alt=""
                  @click.stop="changeVideoUrl"
                />
                <video :src="videoUrl | urlLoad" class="videoBox" v-if="videoUrl"></video>
              </el-upload>
              <span>（只可上传一个，限30S以内）</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 按钮 -->
    <div v-if="disabled == false">
      <button class="cancelButton button" @click="cancel">取消</button>
      <button class="cancelButton button" @click="submit(0)">保存草稿</button>
      <button class="submitButton button" @click="submit(1)">提交上线</button>
    </div>
  </div>
</template>

<script>
import utils from "../../utils/utils";
import regionJson from "@/json/region";
import bus from "../../utils/bus.js";
import { urlLoad } from '/src/filters/index.js'

export default {
  name: "reprocessedPlastic",
  props: {
    data1: Object,
    data: Object,
    disabled: Boolean,
  },
  data() {
    return {
      loading: false,
      productTitle: "",
      price: "",
      number: "",
      addressList: [],
      kind: "",
      producer: "",
      typeNumber: "",
      type: "",
      shape: "",
      trait: [],
      traitData: "",
      level: "",
      sample: "",
      usefulLife: "",
      color: "",
      use: [],
      useData: "",
      shapeOptions: [{ value: "破碎" }, { value: "颗粒" }, { value: "片状" }],
      brand: "",
      brandId: "",
      brandOptions: [],
      useOptions: [
        { value: "电器电子件" },
        { value: "日常用品" },
        { value: "办公用品" },
        { value: "工业配件" },
        { value: "开关面板" },
        { value: "汽车配件" },
        { value: "运动器材" },
        { value: "照明灯具" },
        { value: "包装材料" },
        { value: "通讯器材" },
        { value: "薄壁制品" },
      ],
      handleAddress: [],
      pictureList: [],
      levelOptions: [{ value: "特级" }, { value: "一级" }, { value: "二级" }],
      traitOptions: [
        { value: "流动性好" },
        { value: "普通光面" },
        { value: "环保" },
        { value: "非环保" },
        { value: "无黑点" },
        { value: "高冲击" },
        { value: "高光表面" },
        { value: "性能稳定" },
        { value: "冲击15" },
        { value: "冲击20" },
        { value: "冲击28" },
        { value: "冲击5-7" },
        { value: "冲击10-12" },
      ],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      productId: 0,
      itemList: [{ name: "是" }, { name: "否" }],
      currentIndex: -1,
      userInfo: {},
      draftId: "",
      // 图片
      imgUpload: "https://www.yousubao-01.com/util/file/upload",
      imageList: "",
      imageUrl: "",
      fifthImage: false,
      videoUrl: "",
    };
  },
  watch: {
    data(newData) {
      if (newData) {
        this.changeID();
      }
    },
  },
  created() {
    this.addressList = regionJson;
    this.changeID();
    this.brandList();
    let info = JSON.parse(sessionStorage.getItem("userInfo"));
    this.userInfo = info;
  },
  mounted() {
    // console.log(this.$refs.brandScroll);
    this.$refs.brandScroll.$refs.scrollbar.$refs.wrap.addEventListener(
      "scroll",
      this.brandScolling
    );
    bus.$on("updateDefaultProvince", (val) => {
      this.handleAddress = val;
    });
    bus.$on("updateDefaultCity", (val) => {
      this.handleAddress = val;
    });
  },
  methods: {
    // 已上线/下线列表不同商品跳转
    changeID() {
      // console.log("再生this.data1", this.data1);
      //     console.log("已上线再生data", this.data);
      if (this.data1.brandValue) {
        this.loading = false;
        this.brand = this.data1.brandValue;
        this.brandId = this.data1.brandId;
        this.handleAddress = [
          this.data1.defaultProvince,
          this.data1.defaultCity,
        ];
        this.type = this.currentIndex = 1;
      } else {
        this.loading = false;
        this.productId = this.data.productId;
        this.draftId = this.data.id;
        this.brand = this.data.productName;
        this.productTitle = this.data.title;
        this.price = this.data.price;
        this.number = this.data.number;
        this.type =
          this.data.taxInclusive == 1
            ? (this.currentIndex = 0)
            : (this.currentIndex = 1); //是否含税
        this.sample = this.data.freeTrialNumber;
        this.handleAddress = [
          this.data.deliverySiteProvince,
          this.data.deliverySiteCity,
        ];
        this.usefulLife = this.data.periodOfValidity;
        this.kind = this.data.markName;
        this.producer = this.data.manufacturersName;
        this.color = this.data.productColour;
        this.typeNumber = this.data.productModel;
        this.shape = this.data.productShape;
        this.level = this.data.productLevel;
        this.type = this.itemList[this.currentIndex].name;
        this.imageList = this.data.imageUrl;

        // 产品特性
        this.trait = this.data.productCharacter.split(" ");
        var newTrait = [];
        for (let n = 0; n < this.trait.length; n++) {
          if (this.trait[n]) {
            newTrait.push(this.trait[n]);
          }
        }
        this.trait = newTrait;

        // 产品用途
        this.use = this.data.productPurpose.split(" ");
        var newUse = [];
        for (let i = 0; i < this.use.length; i++) {
          if (this.use[i]) {
            newUse.push(this.use[i]);
          }
        }
        this.use = newUse;

        // 图片
        this.pictureList = this.data.imageUrl.split(",");
        this.pictureList = this.pictureList.map((item) => {
          return {
            name: item,
            url: urlLoad(item),
          };
        });
        // 视频
        this.videoUrl = this.data.videoUrl;
      }
    },
    // 品名列表
    async brandList() {
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      if (this.brandSearch) {
        params.condition = this.brandSearch;
      }
      let res = await this.$apiFun.brandList(params);
      this.brandOptions.push(...res.result.rows);
      this.total = res.result.total;
      // console.log("this.brandOptions ", this.brandOptions);
    },

    // 品名滚动
    brandScolling() {
      let e = this.$refs.brandScroll.$refs.scrollbar.$refs.wrap;
      if (this.noMore) return;
      // 到底时触发 loadMore
      let loadMore = e.scrollHeight - e.scrollTop <= e.clientHeight;
      if (loadMore) {
        this.pageNo += 1;
        this.brandList();
      }
    },

    // 点击是否含税
    selectTax(index) {
      this.currentIndex = index;
      this.type = this.itemList[this.currentIndex].name;
    },

    // 选择交货地
    handleChange(label) {
      this.province = label[0];
      this.city = label[1];
      this.data1.defaultProvince = label[0];
      this.data1.defaultCity = label[1];
      this.data.deliverySiteProvince = label[0];
      this.data.deliverySiteCity = label[1];
    },

    // 图片上传
    successChange(response, file, fileList) {
      var storeList = [];

      // 判断图片长度
      fileList.forEach((item) => {
        var image = "";
        if (item.response) {
          image = item.response.result;
        } else {
          image = item.url;
        }
        storeList.push(image);
      });
      this.imageList = storeList.toString();
      if (fileList.length == 5) {
        this.fifthImage = true;
      }
    },
    hideLogo() {
      setTimeout(() => {
        this.fifthImage = false;
      }, 1000);
    },

    // 产品视频上传
    productSuccess(response, file) {
      this.loading = false;
      this.videoUrl = response.result;
      // console.log("this.videoUrl", this.videoUrl);
      utils.findvideocover(file.url, file);
    },
    progressProduct() {
      this.loading = true;
    },
    hideproduct() {
      setTimeout(() => {
        this.videoUrl = "";
      }, 900);
    },
    changeVideoUrl() {
      this.videoUrl = "";
    },

    // status 0保存 1提交
    async submit(status) {
      if (
        // status为1判断是否填写完整
        // 1)发布供应页跳转进来提交
        status == 1 &&
        this.data1.brandValue !== undefined &&
        (this.brand == "" ||
          this.productTitle == "" ||
          this.price == "" ||
          this.number == "" ||
          this.type == "" ||
          this.sample == "" ||
          (this.province == "" && this.city == "") ||
          (this.data1.defaultProvince == undefined &&
            this.data1.defaultCity == undefined))

        // 手机端下面选项可以不填，用户后台同步
        // ||this.usefulLife == "" ||
        // this.kind == "" ||
        // this.producer == "" ||
        // this.color == "" ||
        // this.typeNumber == "" ||
        // this.shape == "" ||
        // this.level == "" ||
        // this.trait == "" ||
        // this.use == ""
      ) {
        this.$message.error("当前信息填写不完整，请检查并填写完整");
      } else if (
        // 2)已上线/已下线跳转进来提交
        status == 1 &&
        this.data.productName !== undefined &&
        (this.brand == "" ||
          this.productTitle == "" ||
          this.price == "" ||
          this.number == "" ||
          this.type == "" ||
          this.sample == "" ||
          (this.province == "" && this.city == "") ||
          (this.data.deliverySiteProvince == undefined &&
            this.data.deliverySiteCity == undefined) 

          // 手机端下面选项可以不填，用户后台同步
          // ||this.usefulLife == "" ||
          // this.kind == "" ||
          // this.producer == "" ||
          // this.color == "" ||
          // this.typeNumber == "" ||
          // this.shape == "" ||
          // this.level == "" ||
          // this.trait == "" ||
          // this.use == ""
          )
      ) {
        this.$message.error("请检查并填写完整信息");
      } else if (status == 1 && this.imageList == "") {
        this.$message.error("请至少上传一张产品图片");
      } else {
        // 产品用途个数
        if (this.use.length == 3) {
          this.useData = this.use[0] + " " + this.use[1] + " " + this.use[2];
        } else if (this.use.length == 2) {
          this.useData = this.use[0] + " " + this.use[1];
        } else if (this.use.length == 1) {
          this.useData = this.use[0];
        }

        // 产品特性个数
        if (this.trait.length == 3) {
          this.traitData =
            this.trait[0] + " " + this.trait[1] + " " + this.trait[2];
        } else if (this.trait.length == 2) {
          this.traitData = this.trait[0] + " " + this.trait[1];
        } else if (this.trait.length == 1) {
          this.traitData = this.trait[0];
        }

        for (let i = 0; i < this.brandOptions.length; i++) {
          if (this.brand == this.brandOptions[i].name) {
            this.productId = this.brandOptions[i].id;
            break;
          }
        }
        let params = {
          type: "REGENERATION", //再生塑料
          productName: this.brand,
          productId: this.productId,
          title: this.productTitle,
          price: this.price,
          number: this.number,
          taxInclusive: this.type == "是" ? 1 : 0,
          freeTrialNumber: this.sample,
          deliverySiteProvince: this.data1.defaultProvince || this.province,
          deliverySiteCity: this.data1.defaultCity || this.city,
          periodOfValidity: this.usefulLife,
          markName: this.kind,
          manufacturersName: this.producer,
          productColour: this.color,
          productModel: this.typeNumber,
          productShape: this.shape,
          productLevel: this.level,
          productCharacter: this.traitData,
          productPurpose: this.useData,
          imageUrl: this.imageList,
        };
        params.status = status;
        if (this.videoUrl) {
          params.videoUrl = "";
          params.videoUrl = this.videoUrl;
        } else {
          params.videoUrl = "";
        }

        if (status == 1) {
          //status 1提交
          // 已上线，下线列表跳转
          if (this.data.id) {
            params.id = this.draftId;
            params.memberId = this.userInfo.id;
            // console.log("params.id", params.id);
            let res = await this.$apiFun.saveDraft(params);
            if (res.code == 200) {
              this.$message.success("已发布成功");
              this.successBack();
            }
          } else {
            // 发布供应跳转
            console.log(params);
            
            let res = await this.$apiFun.releaseSupply(params);
            if (res.code == 200) {
              this.$message.success("已发布成功");
              this.successBack();
            }
          }
        } else if (status == 0) {
          //status 0保存
          // 已上线，下线列表跳转
          if (this.data.id) {
            params.id = this.draftId;
            params.memberId = this.userInfo.id;
            let res = await this.$apiFun.saveDraft(params);
            if (res.code == 200) {
              this.$message.success("已保存成功");
              this.successBack();
            }
          } else {
            // 发布供应跳转
            let res = await this.$apiFun.releaseSupply(params);
            if (res.code == 200) {
              this.$message.success("已保存成功");
              this.successBack();
            }
          }
        }
      }
    },

    // 保存/提交成功后返回上级页面
    successBack() {
      setTimeout(() => {
        this.$emit("backToMain", {
          typeValue: this.data1.typeValue,
          status: this.data.status || "",
        });
      }, 1800);
    },

    cancel() {
      // console.log("this.data1",this.data1);
      // console.log("this.data",this.data);
      this.$emit("backToMain", {
        typeValue: this.data1.typeValue || "",
        status: this.data.status || "",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.reprocessedPlastic {
  background: #ffffff;
  box-shadow: 0px 3px 20px 0px rgba(230, 230, 230, 0.8);
  border-radius: 10px;
  padding: 0.3rem 0.5rem;
  font-family: Microsoft YaHei;
  height: 100%;
  .title {
    font-size: 0.24rem;
    font-weight: bold;
    color: #333333;
    line-height: 0.3rem;
    margin-bottom: 0.35rem;
    text-align: left;
  }

  // 基本信息
  .companyInformation {
    text-align: left;
    height: auto;

    .content {
      display: flex;
      // 左侧表单
      .left {
        width: 52%;

        .info {
          border-right: 2px solid #efefef;
          // element表单样式
          /deep/ .el-form {
            .companytype {
              font-size: 0.16rem;
              display: flex;
              align-items: center;
              margin-bottom: 25px;
              .leftText {
                width: 110px;
              }
              .selectItem {
                display: flex;
                cursor: pointer;
                margin-left: 0.3rem;
                justify-content: space-between;

                .checkImage {
                  width: 0.22rem;
                  height: 0.22rem;
                }
                .checkbox {
                  width: 0.2rem;
                  height: 0.2rem;
                  border: 1px solid #999999;
                }
              }
              .selectItem:nth-child(2) {
                margin-left: 0;
              }
            }
            .el-input {
              width: 90%;
            }
            .el-textarea {
              width: 90%;
              height: 4.9rem;
            }
            .el-checkbox__inner {
              width: 0.2rem;
              height: 0.2rem;
              border: 1px solid #999999;
              border-radius: 2px;
              &::after {
                height: 0.12rem;
                left: 0.07rem;
              }
            }
            // 点击样式
            .is-checked {
              .el-checkbox__inner {
                background-color: #f42551;
              }
            }

            .el-form-item__label,
            .el-input__inner,
            .el-textarea__inner,
            .el-checkbox__label {
              font-size: 0.16rem;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: #333333;
            }

            .el-input__inner,
            .el-input__count {
              background-color: #f5f5f5;
            }

            .el-textarea__inner {
              height: 100%;
              background-color: #f5f5f5;
            }

            .el-select,
            .el-cascader {
              width: 100%;
              .el-tag.el-tag--info {
                font-size: 0.16rem;
                background: transparent;
                border: none;
                color: #333333;
                .el-tag__close {
                  display: none;
                }
              }
            }

            .el-form-item__label {
              width: 110px !important;
              text-align: left;
            }
            .el-form-item__content {
              margin-left: 110px !important;
              .word {
                position: absolute;
                right: 0.5rem;
                font-size: 0.16rem;
                font-weight: 400;
                color: #333333;
              }
            }
          }
        }
      }

      // 右侧上传处
      .right {
        width: 47%;
        // background: skyblue;
        margin-left: 3%;

        .store,
        .video {
          display: flex;
          justify-content: space-evenly;
          font-size: 0.16rem;
          font-weight: 400;
          margin-bottom: 0.3rem;
          .leftText {
            width: 35%;
            color: #333333;
          }
          .uploadPlace {
            width: 46.9%;
            color: #999999;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            /deep/ .el-upload--picture-card {
              width: 1rem;
              height: 1rem;
              background: #f5f5f5;
              border-radius: 5px;
              cursor: pointer;
              margin-bottom: 0.1rem;
              border: none;
              position: relative;

              .uplogo {
                height: 100%;
                position: relative;
                display: flex;
                justify-content: center;
                flex-direction: column;
                align-items: center;
                .image {
                  height: 0.36rem;
                  width: 0.36rem;
                }
                .text {
                  line-height: 0.3rem;
                }
              }
              .closeIcon {
                position: absolute;
                top: -0.1rem;
                right: -0.1rem;
                z-index: 2;
                width: 0.2rem;
              }
              .videoBox {
                width: 1rem;
                height: 1rem;
                object-fit: fill;
                position: absolute;
                top: 0;
                left: 0;
              }
            }

            .hide /deep/.el-upload--picture-card {
              display: none;
            }

            /deep/ .el-upload-list--picture-card .el-upload-list__item {
              width: 1rem;
              height: 1rem;
            }
          }
        }

        .store {
          // height: 40%;
          height: auto;
        }

        .video {
          .uploadPlace {
            display: flex;
            flex-direction: column;
          }
        }
      }
    }
  }

  // 按钮
  .button {
    width: 1.9rem;
    height: 0.4rem;
    border-radius: 5px;
    font-size: 0.16rem;
    font-weight: bold;
    color: #ffffff;
    line-height: 0.3rem;
    border: 1px solid;
    margin-top: 0.8rem;
    cursor: pointer;
    margin-left: 0.2rem;
  }
  .cancelButton {
    color: #333333;
  }
  .submitButton {
    border: none;
    background: #f42551;
    color: #ffffff;
  }
}
</style>